<?php
session_start();
function buildMatrix ($n, $m) {
	$matrix = array();
	echo "<form method=\"post\">";
	for ($i = 0; $i < $n; $i++) {
		echo "<div>";
		for ($j = 0; $j < $m; $j++) {
			echo "<input type=\"text\" name=\"$i$j\"/>";
		}
		echo "</div>";
	}
	echo "<input type=\"submit\" name=\"submit2\"/></form>";
	return $matrix;
}
function multiplyMatrix($matrix, $num, $n, $m){
	for ($i = 0; $i < $n; $i++) {
		echo "<div>";
		for ($j = 0; $j < $m; $j++) {
			echo "<div class=\"m\"> ". $matrix[$i][$j] * $num. " </div>";
		}
		echo "</div>";
	}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Matrix</title>
<style>
.m {
	padding: 10px;
	border: 1px solid;
	margin: 5px;
	float: left;
}
</style>
</head>
    <body>
	<?php 
	if (isset($_POST['reset'])){
		session_destroy();
		unset($_SESSION);
	}
	if (isset($_POST['submit'])){
		$rows = isset($_POST['row'])? $_POST['row'] : 0;
		$cols = isset($_POST['col'])? $_POST['col'] : 0;
		$_SESSION['n'] = $rows;
		$_SESSION['m'] = $cols;
		$matrix = buildMatrix ($rows, $cols);
		exit();
	}
	if (isset($_POST['submit2'])){
		$n = $_SESSION['n'];
		$m = $_SESSION['m'];
		$matrix = array();
		for ($i = 0; $i < $n; $i++) {
			for ($j = 0; $j < $m; $j++) {
				$matrix[$i][$j] = $_POST[$i.$j];
			}
		}
		$_SESSION['matrix'] = $matrix;
		echo "<form method=\"post\"><input type=\"text\" name=\"mult\"/><input type=\"submit\" name=\"submit3\"/></form>";
		exit();
	}
	if (isset($_POST['submit3'])){
		$n = $_SESSION['n'];
		$m = $_SESSION['m'];
		$matrix = $_SESSION['matrix'];
		$mult = isset($_POST['mult'])? $_POST['mult'] : 0;
		multiplyMatrix($matrix, $mult, $n, $m);
		echo "<form method=\"post\"><input type=\"submit\" name=\"reset\" value=\"reset\"/></form>";
		exit();
	}
	?>
	<form method="post">
		<p>Rows: <input type="text" name="row"/></p>
		<p>Columns: <input type="text" name="col"/></p>
		<p><input type="submit" value="submit" name="submit"/></p>
	</form>
    </body>
</html>